home *** CD-ROM | disk | FTP | other *** search
- Path: jaxnet.jaxnet.com!jax!garyg
- From: garyg@jax.jaxnet.com (Gary M. Greenberg)
- Newsgroups: comp.lang.c
- Subject: Re: Arrays of strings
- Date: 17 Feb 1996 00:04:21 GMT
- Organization: Southeast Network Services, Inc.
- Message-ID: <4g3625$f0m@jaxnet.jaxnet.com>
- NNTP-Posting-Host: jax.jaxnet.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Larry DiGiovanni (ldigiova@nova.umuc.edu) wrote:
-
- : I'm trying to read lines of a text file and load those lines into an
- : array. I have a couple of questions...
-
- Note: Someone will no doubt correct any incorrect terminology.
-
- : 1. How do I declare the array to contain the text. When it is declared,
- : I will not know how many lines are in the text file. char **txtarray?
-
- Yes, that can work. "char **txtarray;" now is an uninitialized pointer
- of pointers to character arrays <I hope I stated that correctly>.
-
- : 2. How do I allocate the space for the data once I know how many lines
- : are in the text file? txtarray = malloc((size_t)(nelements))?
-
- Make sure to #include <stdlib.h> for malloc, and then do something like:
- /* assuming each line is one of your character arrays, read the file
- and count the number of lines. Then you can ... */
- txtarray=malloc(X * (char **)); /* X == number of char arrays */
- /* do the error checking ... */
-
- Note that this only allocates space for **txtarray; nothing is allocated for
- each of the individual character arrays yet.
-
- : 3. What is the best way to read from the text file into the array
- : elements? fscanf? fgets?
-
- I use fgets, and process it accordingly, stripping off the newline, and then
- assign each line <character array, using assumptions above> to one element
- of **txtarray. you must malloc each character array and error check
- accordingly.
-
- : I have had no success reading directly into the
- : elements with these two functions. I don't understand why, but it may be
- : related to my poor understanding of (1) and (2) above as well.
-
- Post some of the not-working attempt. It is the best way to learn, honest.
-
- : Any help would be greatly appreciated. TIA
-
- : Larry DiGiovanni
-
- another C neophyte,
-
- gary /* the Sorcerer's Apprentice */
-
- "Why do we have to hide from the police, Daddy?"
- "Because we use vi, honey. They use emacs."
- "Unless we're on the Mac. Then we use BBEdit 'cause 'It doesn't suck.'"
-